package main;

import processing.core.PApplet;
import processing.core.PImage;

public class RequestImage extends PApplet {

    int imageCount = 12;
    PImage[] pImages = new PImage[imageCount];
    float imgWidth;

    // keeps track of loaded images(true or false)
    boolean[] loadStates = new boolean[imageCount];

    // for loading animation
    float loaderX, loaderY, theta;

    @Override
    public void settings() {
        size(640, 360);
    }

    @Override
    public void setup() {
        imgWidth = width/imageCount;

        // load images asynchronously
        for(int i = 0; i < imageCount; i++) {
            int y = i + 8;
            pImages[i] = requestImage("C:\\Users\\Hyper\\Pictures\\Screenshots\\Screenshot (" + y +").png");
        }
    }

    @Override
    public void draw() {
        background(0);
        // Start loading animation
        runLoaderAni();

        for (int i = 0; i < pImages.length; i++){
            // Check if individual images are fully loaded
            if ((pImages[i].width != 0) && (pImages[i].width != -1)){
                // As images are loaded set true in boolean array
                loadStates[i] = true;
            }
        }
        // When all images are loaded draw them to the screen
        if (checkLoadStates()){
            drawImages();
        }
    }

    void drawImages() {
        int y = (height - pImages[0].height) / 2;
        for (int i = 0; i < pImages.length; i++){
            image(pImages[i], width/pImages.length*i, y, pImages[i].height, pImages[i].height);
        }
    }
    // Loading animation
    void runLoaderAni(){
        // Only run when images are loading
        if (!checkLoadStates()){
            ellipse(loaderX, loaderY, 10, 10);
            loaderX += 2;
            loaderY = height/2 + sin(theta) * (height/8);
            theta += PI/22;
            // Reposition ellipse if it goes off the screen
            if (loaderX > width + 5){
                loaderX = -5;
            }
        }
    }

    // Return true when all images are loaded - no false values left in array
    boolean checkLoadStates(){
        for (int i = 0; i < pImages.length; i++){
            if (loadStates[i] == false){
                return false;
            }
        }
        return true;
    }
}
